package com.wct.demo.gui;

import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.util.concurrent.ExecutionException;

/**
 * @author WEI (Email:changtan20000@163.com)
 * @description
 * @date 2019/12/22 20:53
 */
@Slf4j
public class SwingWorkerDemo extends JFrame {

    private JLabel label;

    public void createAndShowGUI() {
        label = new JLabel("Hello World!");
        label.setSize(150, 50);
        add(label);
        setSize(200, 100);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        pack();
        setVisible(true);
    }

    private void update(String value){
        SwingWorker worker = new SwingWorker<String, Void>() {
            @Override
            public String doInBackground() {
                return value;
            }
            @Override
            public void done() {
                try {
                    label.setText(get());
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }
        };
        worker.execute();
    }

    public static void main(String[] args) {

        SwingWorkerDemo swingWorkerDemo = new SwingWorkerDemo();
        SwingUtilities.invokeLater(swingWorkerDemo::createAndShowGUI);

        swingWorkerDemo.update("hello");
    }
}
